package com.weaving.monitor.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 疵点类型工具类
 * 
 * 功能说明：
 * 1. 提供疵点类型编号到名称的映射
 * 2. 将疵点类型列表转换为可读的字符串
 * 3. 用于质量状态显示
 * 
 * @author 系统开发团队
 * @version 1.0
 * @since 2024-01-01
 */
public class FlawTypeUtil {
    
    /**
     * 疵点类型映射表
     */
    private static final Map<Integer, String> FLAW_TYPE_MAP;
    
    static {
        Map<Integer, String> map = new HashMap<>();
        map.put(0, "停车位");
        map.put(1, "横条");
        map.put(2, "断头");
        map.put(3, "长断头");
        map.put(4, "油污");
        map.put(5, "漏针");
        map.put(6, "其他");
        map.put(8, "抛丝");
        map.put(9, "吊丝");
        map.put(10, "勾丝");
        map.put(11, "油污丝");
        map.put(12, "导电丝异常");
        map.put(13, "毛针");
        map.put(14, "其他");
        map.put(16, "破洞");
        map.put(17, "隐横路");
        map.put(18, "坏边右");
        map.put(21, "拼缝");
        map.put(22, "吊丝");
        map.put(23, "色丝（僵丝）");
        map.put(24, "盘头印");
        map.put(25, "轮胎印");
        map.put(26, "叉针");
        map.put(27, "钓伤");
        map.put(28, "漏针");
        map.put(29, "下边");
        map.put(33, "毛丝");
        map.put(34, "粘丝");
        map.put(35, "理边丝");
        map.put(37, "盘头毛刺");
        map.put(38, "勾丝");
        map.put(48, "理直条");
        FLAW_TYPE_MAP = Collections.unmodifiableMap(map);
    }
    
    /**
     * 根据疵点类型编号获取疵点类型名称
     * 
     * @param typeCode 疵点类型编号
     * @return 疵点类型名称，如果不存在则返回"未知类型"
     */
    public static String getFlawTypeName(Integer typeCode) {
        if (typeCode == null) {
            return "未知类型";
        }
        return FLAW_TYPE_MAP.getOrDefault(typeCode, "未知类型");
    }
    
    /**
     * 将疵点类型列表转换为逗号分隔的字符串
     * 
     * @param flawTypes 疵点类型编号列表
     * @return 逗号分隔的疵点类型名称字符串
     */
    public static String convertFlawTypesToString(List<Integer> flawTypes) {
        if (flawTypes == null || flawTypes.isEmpty()) {
            return "";
        }
        
        return flawTypes.stream()
                .map(FlawTypeUtil::getFlawTypeName)
                .distinct() // 去重
                .collect(Collectors.joining(","));
    }
    
    /**
     * 根据产品ID查询疵点类型并转换为字符串
     * 
     * @param productId 产品ID
     * @param prodFlawMapper ProdFlawMapper实例
     * @return 逗号分隔的疵点类型名称字符串
     */
    public static String getFlawTypesStringByProductId(String productId, com.weaving.monitor.mapper.ProdFlawMapper prodFlawMapper) {
        if (productId == null || productId.trim().isEmpty()) {
            return "";
        }
        
        try {
            List<Integer> flawTypes = prodFlawMapper.selectFlawTypesByProductId(productId);
            return convertFlawTypesToString(flawTypes);
        } catch (Exception e) {
            System.err.println("查询产品疵点类型失败，产品ID: " + productId + ", 错误: " + e.getMessage());
            return "";
        }
    }
}
